<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>8 模板语法-指令</title>
    <script src="https://cdn.jsdelivr.net/npm/axios@0.12.0/dist/axios.min.js"></script>
    <script src="js/vue.global.js"></script>
</head>
<body>
<div id="watch-example">
    <p>
        输入一个问题，以 ? 号结尾输出答案:
        <input v-model="question" />
    </p>
    <p>{{ answer }}</p>
</div>
<script>
    const watchExampleVM = Vue.createApp({
        data() {
            return {
                question: '',
                answer: '每个问题结尾需要输入 ? 号。'
            }
        },
        watch: {
            // 每当问题改变时，此功能将运行，以 ? 号结尾
            question(newQuestion, oldQuestion) {
                if (newQuestion.indexOf('?') > -1) {
                    this.getAnswer()
                }
            }
        },
        methods: {
            getAnswer() {
                this.answer = '加载中...'
                axios
                    .get('https://yesno.wtf/api')
                    .then(response => {
                        this.answer = response.data.answer
                    })
                    .catch(error => {
                        this.answer = '错误! 无法访问 API。 ' + error
                    })
            }
        }
    }).mount('#watch-example')
</script>
</body>
</html>